package org.kl.bpm.web.conf;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;

import org.activiti.engine.HistoryService;
import org.activiti.engine.ManagementService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.impl.interceptor.Command;
import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.User;
import org.kl.bf.entity.easyui.ComboBox;
import org.kl.bf.entity.easyui.EasyuiGrid;
import org.kl.bf.entity.workflow.ETask;
import org.kl.bf.service.basic.UserService;
import org.kl.bf.web.base.BasicController;
import org.kl.bpm.cmd.JumpCmd;
import org.kl.bpm.cmd.ListActivityCmd;
import org.kl.bpm.cmd.MigrateCmd;
import org.kl.bpm.entity.conf.BpmConfBase;
import org.kl.bpm.service.conf.BpmConfBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.mapper.BeanMapper;
import org.springside.modules.utils.Collections3;
import org.springside.modules.web.MediaTypes;

/**
 * 工作流相关的控制管理
 * 
 * @Author hqm
 * @CreateTime 2014年6月10日 下午11:04:33
 */
@Controller
@RequestMapping(value = "/bpm/console")
public class BpmConsoleController extends BasicController {
	@Autowired
	private UserService userService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private ManagementService managementService;
	@Autowired
	private RepositoryService repositoryService;

	@Autowired
	private BpmConfBaseService bpmConfBaseService;

	/**
	 * 打开页面-->>所有任务
	 * 
	 * @return
	 */
	@RequestMapping(value = "to-console-listTasks", produces = MediaTypes.JAVASCRIPT_UTF_8)
	public String to_listTasks() {
		return "bpm/console-listTasks";
	}

	/**
	 * 我发起的流程实例
	 * 
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "console-listTasks", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String listTasks(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery();
		List<HistoricTaskInstance> taskList = historicTaskInstanceQuery.orderByHistoricTaskInstanceEndTime().desc()
				.listPage(((pageNumber - 1) * pageSize), pageSize);
		List<ETask> epiList = new ArrayList<ETask>();
		for (HistoricTaskInstance t : taskList) {
			ETask et = BeanMapper.map(t, ETask.class);
			epiList.add(et);
			if (StringUtils.isNotBlank(t.getAssignee())) {
				User user = userService.getUser(t.getAssignee());
				et.setAssigneeName(user == null ? "" : user.getTrueName());
			}
		}
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(epiList);
		grid.setTotal((int) historicTaskInstanceQuery.count());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	/**
	 * 准备需要跳转的流程用户任务节点下拉菜单
	 */
	@RequestMapping(value = "activityCombobox", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String activityCombobox(@RequestParam(value = "executionId", defaultValue = "-1") String executionId) {
		Command<Map<String, String>> cmd = new ListActivityCmd(executionId);
		Map<String, String> activityMap = managementService.executeCommand(cmd);
		if (activityMap.isEmpty()) {
			return "{}";
		}
		List<ComboBox> combobox = new ArrayList<ComboBox>();
		for (String key : activityMap.keySet()) {
			ComboBox one = new ComboBox();
			one.setId(key);
			one.setText(activityMap.get(key));
			one.setValue(key);
			combobox.add(one);
		}
		return jsonMapper.toJson(combobox);
	}

	/**
	 * 自由跳转
	 * 
	 * @param executionId
	 * @param activityId
	 * @return
	 */
	@RequestMapping(value = "jump", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String jump(@RequestParam("executionId") String executionId, @RequestParam("activityId") String activityId) {
		Command<Object> cmd = new JumpCmd(executionId, activityId);
		managementService.executeCommand(cmd);
		return ajaxMsg("跳转成功", true, null);
	}

	/**
	 * 准备流程实例迁移的流程定义下拉菜单
	 */
	@RequestMapping(value = "pdCombobox", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String processDefinitionCombobox() {
		List<BpmConfBase> bcbList = bpmConfBaseService.getAllBpmConfBase();
		if (Collections3.isEmpty(bcbList)) {
			return "{}";
		}
		List<ComboBox> combobox = new ArrayList<ComboBox>();
		for (BpmConfBase bcb : bcbList) {
			ComboBox one = new ComboBox();
			one.setId(bcb.getProcessDefinitionId());
			one.setText(bcb.getProcessDefinitionId());
			one.setValue(bcb.getProcessDefinitionId());
			combobox.add(one);
		}
		return jsonMapper.toJson(combobox);
	}

	/**
	 * 流程实例迁移
	 * 
	 * @param executionId
	 * @param activityId
	 * @return
	 */
	@RequestMapping(value = "migrate", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String migrate(@RequestParam("processInstanceId") String processInstanceId,
			@RequestParam("processDefinitionId") String processDefinitionId) {
		try {
			managementService.executeCommand(new MigrateCmd(repositoryService, processInstanceId, processDefinitionId));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ajaxMsg("迁移失败[" + e.getMessage() + "]", false, null);
		}
		return ajaxMsg("迁移至[" + processDefinitionId + "]成功", true, null);
	}
}
